/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package com.landmark;

//import antlr.Parser;
import java.io.FileWriter;
import java.util.Enumeration;
import java.util.Hashtable;
//import javax.lang.model.element.Element;
//import javax.lang.model.util.Elements;
import javax.swing.JTextArea;
import javax.swing.SwingWorker;
//import javax.swing.text.Document;
import org.htmlparser.Node;
//import javax.xml.soap.Node;
import org.htmlparser.Parser;
import org.htmlparser.filters.HasAttributeFilter;
import org.htmlparser.nodes.TagNode;
import org.htmlparser.nodes.TextNode;
import org.htmlparser.util.NodeIterator;
import org.htmlparser.util.NodeList;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
//import org.jsoup.nodes.TextNode;

//import org.w3c.dom.NodeList;
//import org.w3c.dom.traversal.NodeIterator;

/**
 *
 * @author computer
 */
public class ASPCat extends SwingWorker<Boolean, Boolean> {

    FileWriter fw = null;
    FileWriter errorFile = null;
    int fileNumber = 0;
    int pageNo;
    StringBuffer sb = new StringBuffer();
    Hashtable<String, String> htModelLinks = new Hashtable<String, String>();
    String status = "";
    JTextArea txtArea;

    @Override
    protected Boolean doInBackground() throws Exception {
        start();
        return true;
    }

    @Override
    protected void done() {
        Util.taskCompleteMsg(status);
    }

    public void start() {
        try {
            String dirName = "./outputs";

            Util.createDirectory(dirName);

            int[] pageCount = {18, 3, 2, 3, 3};
            String[] categoryViewAll = {"3", "1", "5", "33", "4"}; // The category name/code

            txtArea = Util.createOutputFile("ASP");
            HelperBean helperBean = Util.getHelperBean();

            fw = new FileWriter(helperBean.getOutputFile());
            errorFile = new FileWriter(helperBean.getErrorFile());

            // Here we get all the search pages from page 0 to 9 which we know by seeing the site
            for (int i = 0; i < categoryViewAll.length; i++) {
                for (pageNo = 1; pageNo <= pageCount[i]; pageNo++) {
                    if (Util.getHelperBean().isTerminateCurrentProcess()) {
                        break;
                    }
                    String str = "http://www.asponlinestore.com/category_s/"+ categoryViewAll[i] +".htm?searching=Y&sort=5&cat="+ categoryViewAll[i] +"&show=12&page="+ pageNo;
                    txtArea.setText(str);
                    txtArea.paintImmediately(txtArea.getVisibleRect());
                    processCategoryPage(str, false);
                }
            }

            txtArea.append("\nFiles are located at : \n" + helperBean.getOutputFile().getAbsolutePath() + "\n" + helperBean.getErrorFile().getAbsolutePath() + "\n");
            txtArea.append("Total products : " + htModelLinks.size() + "\n");
            txtArea.paintImmediately(txtArea.getVisibleRect());

            iterateCollection(htModelLinks);

            if (fw != null) {
                fw.close();
            }

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fw != null) {
                    fw.close();
                }
            } catch (Exception e1) {
                // TODO: handle exception
            }
        }
        status = "Done processing.";
        if (Util.getHelperBean().isTerminateCurrentProcess()) {
            status = "Process Terminated";
        }
        txtArea.append("\n" + status);
    }

    /**
     *
     * @param htLinks
     */
    private void iterateCollection(Hashtable<String, String> htLinks) {
        try {
            Enumeration<String> keys = htLinks.keys();
            while (keys.hasMoreElements()) {
                if (Util.getHelperBean().isTerminateCurrentProcess()) {
                    break;
                }
                String key = (String) keys.nextElement();
                
                txtArea.setText("Processing page: " + key + "\n");
                txtArea.paintImmediately(txtArea.getVisibleRect());
                
                sb = new StringBuffer();
                
                fw.write("\n" + key + "\n");
                processModels(htLinks.get(key).toString());
                fw.write(sb.toString().replaceAll("\n", "").replaceAll("\r", "").replaceAll("    ", ""));
                fw.write("\n");
                fw.flush();
            }
        } catch (Exception e) {
        }
    }

    /**
     *
     * @param aUrl
     */
    private void processModels(String aUrl) {
        try {

            Parser parser = Util.getParserFromUrl(aUrl, null);

            NodeList nl = parser.parse(null);

            NodeList tableNodes = nl.extractAllNodesThatMatch(new HasAttributeFilter("class", "colors_pricebox"), true);
            if( tableNodes.size() == 0 ) {
                tableNodes = nl.extractAllNodesThatMatch(new HasAttributeFilter("id", "ProductDetail_ProductDetails_div"), true);
            }
            Node targetTableNode = tableNodes.elementAt(0);// retrives the table content where the description starts which we are intersetd in.			
            
            iterateTag(targetTableNode);

        } catch (Exception e) {
            try {
                errorFile.write(aUrl + " \n" + e.getMessage() + " \n");
                errorFile.flush();
                //e.printStackTrace();
            } catch (Exception e1) {
                // TODO: handle exception
            }
        }
    }

    /**
     *
     * @param aNodeList
     */
    private void iterateTag(Node aNodeList) {
        if (aNodeList instanceof TextNode) {
            // downcast to TextNode
            TextNode text = (TextNode) aNodeList;

            sb.append(text.getText());
        } else if (aNodeList instanceof TagNode) {
            // downcast to TagNode
            TagNode tag = (TagNode) aNodeList;

            NodeList nl = tag.getChildren();
            if (null != nl) {
                try {
                    for (NodeIterator i = nl.elements(); i.hasMoreNodes();) {
                        iterateTag(i.nextNode());
                    }
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }

    private void processCategoryPage(String aUrl, boolean isModelPage) {
        try {
            Document doc = Jsoup.connect(aUrl).get();

            Elements elements = doc.select("table.v65-productDisplay").select("a[href]");

            for (Element element : elements) {

                String absoluteUrl = element.attr("abs:href");
                htModelLinks.put(absoluteUrl, absoluteUrl);
            }
        } catch (Exception e) {
            try {
                errorFile.write(aUrl + " \n" + e.getMessage() + " \n");
                errorFile.flush();
                e.printStackTrace();
            } catch (Exception e1) {
                // TODO: handle exception
            }
            e.printStackTrace();
        }
    }

}
